"""
Pixiv作者监控主程序
"""
import logging
import sys
import os
from config import LOG_CONFIG, create_directories
from ui import PixivMonitorUI

def setup_logging():
    """设置日志"""
    create_directories()

    # 配置日志格式
    logging.basicConfig(
        level=logging.DEBUG,  # 设置为DEBUG级别以查看更多信息
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        handlers=[
            # 控制台输出
            logging.StreamHandler(sys.stdout),
            # 文件输出
            logging.FileHandler(LOG_CONFIG["log_file"], encoding='utf-8', mode='a')
        ]
    )

    # 设置文件日志级别
    file_handler = logging.FileHandler(LOG_CONFIG["log_file"], encoding='utf-8')
    file_handler.setLevel(logging.DEBUG)
    file_handler.setFormatter(logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    ))

    # 添加文件处理器到根日志器
    logging.getLogger().addHandler(file_handler)

def main():
    """主函数"""
    # 设置日志
    setup_logging()

    logger = logging.getLogger(__name__)
    logger.info("=== Pixiv监控程序启动 ===")

    try:
        # 创建并运行UI
        app = PixivMonitorUI()

        # 设置关闭事件
        app.root.protocol("WM_DELETE_WINDOW", app.on_closing)

        # 运行应用
        app.run()

    except Exception as e:
        logger.error(f"程序运行出错: {str(e)}", exc_info=True)
        print(f"程序运行出错: {str(e)}")
        sys.exit(1)

    finally:
        logger.info("=== Pixiv监控程序退出 ===")

if __name__ == "__main__":
    main()